import {
  Breadcrumb,
  Button,
  Card,
  Form,
  Radio,
  Select,
  DatePicker,
  Table,
  Tag,
  Space,
  message,
  Modal,
} from 'antd';
import { delArticlesAPI, getArticlesAPI, getChannelsAPI } from 'api/article';
import React, { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import errorPic from 'assets/error.png';
import { FormOutlined, DeleteOutlined } from '@ant-design/icons';
import Channel from 'components/Channel';
import { useHistory } from 'react-router-dom';

const { Option } = Select;
const { RangePicker } = DatePicker;
export default function ArticleList() {
  const history = useHistory();

  const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ];
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: (value) => {
        if (!value.images.length) {
          return <img width={100} height={60} src={errorPic} alt="" />;
        } else {
          return <img width={100} src={value.images[0]} alt="" />;
        }
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render(value) {
        const findTag = articleStatus.find((item) => item.id === value);
        return (
          <div>
            <Tag color={findTag?.color}>{findTag?.name}</Tag>
          </div>
        );
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
      key: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
      key: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'coment_count',
      key: 'coment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
      key: 'like_count',
    },
    {
      title: '操作',
      render: (value, record) => (
        <Space>
          <Button
            type="primary"
            shape="circle"
            icon={<FormOutlined />}
            onClick={() => history.push('/edit/' + record.id)}
          />
          <Button
            type="dashed"
            shape="circle"
            icon={<DeleteOutlined />}
            onClick={() => handleDelArticles(record.id)}
          />
        </Space>
      ),
    },
  ];
  /*   useState */
  const [articlesData, setArticlesData] = useState({});

  // useEffect 请求数据
  useEffect(() => {
    getArticles();
  }, []);

  /*  useRef */
  // 使用Ref存储请求参数
  const formDataRef = useRef(null);
  // 当点击时存储页数信息
  const pageRef = useRef(null);

  /* 方法函数 */
  // 删除文章列表
  const handleDelArticles = (id) => {
    Modal.confirm({
      title: '温馨提示',
      content: '您确定删除这篇文章?',
      onOk: async () => {
        // 使用接口删除
        await delArticlesAPI(id);
        // 重新获取文章列表
        const formData = formDataRef.current || {};
        const pageSetting = pageRef.current || {};
        console.log(pageSetting);

        // 分页功能删除最后一条数据返回上一页
        // 1 计算总页数
        const totalPage = Math.ceil((articlesData.total_count - 1) / pageSetting.per_page);
        // 2 判断是否删除最后一条信息
        pageSetting.page = pageSetting.page > totalPage ? totalPage : pageSetting.page;
        getArticles({ ...formData, ...pageSetting });
        message.success('删除成功', 1);
      },
    });
  };

  // 获取文章列表函数
  const getArticles = async (params = {}) => {
    const res = await getArticlesAPI(params);
    setArticlesData(res.data);
  };
  // 筛选提交
  const handleSubmit = (value) => {
    console.log(value);
    // 定义一个formData 传给后台
    const formData = { ...value };
    // 根据api文档 状态为全部不传值
    if (value.status === -1) {
      // 原生删除方法 删除键
      delete formData.status;
    }

    // 日期处理
    if (value.date) {
      formData.begin_pubdate = formData.date[0].startOf('date').format('YYYY-MM-DD HH:mm:ss');
      formData.end_pubdate = formData.date[1].endOf('date').format('YYYY-MM-DD HH:mm:ss');
      delete formData.date;
    }
    formDataRef.current = formData;
    getArticles(formData);
  };
  return (
    <div style={{ paddingTop: 24 }}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form onFinish={handleSubmit} initialValues={{ status: -1, channel_id: 0 }}>
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="频道" name="channel_id">
            <Channel style={{ width: 200 }}></Channel>
          </Form.Item>

          <Form.Item label="日期" name="date">
            <RangePicker />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>

        {/* dataSource 控制每行数据  columns控制列显示 */}
        <Table
          dataSource={articlesData.results}
          columns={columns}
          rowKey="id"
          pagination={{
            onChange: (page, pageSize) => {
              pageRef.current = { page, per_page: pageSize };
              // 点击不同分页请求数据
              getArticles({ page, per_page: pageSize, ...(formDataRef.current || {}) });
            },
            current: articlesData.page,
            position: ['bottomCenter'],
            defaultCurrent: 1,
            total: articlesData.total_count,
            pageSize: articlesData.per_page,
            pageSizeOptions: [2, 5, 10, 20, 30],
          }}
        />
      </Card>
    </div>
  );
}
